package net.wang.concurrency.test.count;

import lombok.extern.slf4j.Slf4j;
import net.wang.concurrency.annoations.ThreadSafe;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@SuppressWarnings("ALL")
@Slf4j
@ThreadSafe
public class CountTestSync {

    public static int clientTotal = 5000;
    public static int threadTotal = 200;
    public static int count = 0;

    @Test
    public void notThreadSafeTest() throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.info("exception : {}", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("count = {}", count);
    }

    /**
     * 多个线程执行到add方法
     */
    public synchronized void add() {
        count++;
    }

}
